#include <iostream>
#include "opencv2/opencv.hpp"
#include "face.h"
#include <iostream>
#include <cstring>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <iostream>
#include <chrono>
#include <ctime>

using namespace std;
using namespace cv;
using namespace aip;

int main()
{
    
 
    VideoCapture cap(0); 
    if (!cap.isOpened())
    {
        cout << "open fail" << endl;
        return -1;
    } 

    CascadeClassifier Classifier("/usr/share/opencv/haarcascades/haarcascade_frontalface_alt2.xml ");

    std::string app_id = "115637414";
    std::string api_key = "LuqtWCeWeloiEORqM7cuvMfi";
    std::string secret_key = "G1VvB3dQY4C0Spr85ReYN9gGs9lgVnYO";
    aip::Face client(app_id,api_key,secret_key);
    

    Mat ColorImage;
    Mat GrayImage;
    vector<Rect> Allface;
    Mat MatFace;
    vector<uchar> JpgFace;
    string Base64Face;
    Json::Value result;
    
    std::string image_type = "BASE64";
    Json::Value jsonMap;
       auto now = chrono::system_clock::now();
    // 转换为字符串格式
    char buffer[26];
    // 转换为时间_t

    for(;;){
        
        cap >> ColorImage;
        cvtColor(ColorImage,GrayImage,CV_BGR2GRAY);
        equalizeHist(GrayImage,GrayImage);
        Classifier.detectMultiScale(GrayImage,Allface, 1.1, 3, 0 | CASCADE_SCALE_IMAGE, Size(30, 30));
        cout << "Faces detected: " << Allface.size() << endl;
        if(Allface.size())
        {
            
            rectangle(GrayImage,Allface[0],Scalar(255,255,255));
            MatFace = GrayImage(Allface[0]);
            imencode(".jpg",MatFace,JpgFace);

            Base64Face = base64_encode((char*)JpgFace.data(),JpgFace.size());
            result =  client.face_search_v3(Base64Face,image_type,"zyf",jsonMap);

            if(!result["result"].isNull())
            {
                if(result["result"]["user_list"][0]["score"].asInt() > 80)
                {
                    time_t now_time_t = chrono::system_clock::to_time_t(now);
                    ctime_r(&now_time_t, buffer); 
                    cout << result["result"]["user_list"][0]["user_id"] << endl;

                    cout << buffer  << endl;

                }
            }

            
        }

    }
    return 0;
}
